/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hiof.moraa.server.dao;

import com.hiof.moraa.server.service.model.UserInfo;
import com.hiof.moraa.mapping.TblUser;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Bergy
 */
public class HibernateUserDAOImp implements UserDAO {

    private SessionFactory factory;

    public SessionFactory getFactory() {
        return factory;
    }

    public void setFactory(SessionFactory factory) {
        this.factory = factory;
    }

    @Override
    public UserInfo getUserInfoFromUsername(String username) {
        Session session = factory.getCurrentSession();
        String hql = "from TblUser user where user.username = :username";
        Query query = session.createQuery(hql);
        query.setString("username", username);
        TblUser user = (TblUser) query.uniqueResult();
        UserInfo userInfo = convert2UserInfo(user);
        return userInfo;
    }

    @Override
    public TblUser getTbleUserFromUsername(String username) {
        Session session = factory.getCurrentSession();
        String hql = "from TblUser user where user.username = :username";
        Query query = session.createQuery(hql);
        query.setString("username", username);
        TblUser user = (TblUser) query.uniqueResult();
        return  user;
    }

    @Override
    public UserInfo getUserInfoFromUserId(int userId) {
        TblUser user = (TblUser) factory.getCurrentSession().get(TblUser.class, userId);
        UserInfo userInfo = convert2UserInfo(user);
        return userInfo;
    }

    @Override
    public TblUser getTbleUserFromUserId(int userId) {
        TblUser user = (TblUser) factory.getCurrentSession().get(TblUser.class, userId);
        return  user;
    }

    private UserInfo convert2UserInfo(TblUser user) {
        if (user != null) {
            UserInfo userInfo = new UserInfo(user.getId(), user.getUsername(), user.getFirstName() + " " + user.getLastName(), user.getProfilePicture(), user.getPhone(), user.getAge(), user.getMaxHeartRate());
            return userInfo;
        } else {
            return null;
        }
    }
}
